package com.tskj.leonsu.controller;

import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.service.SystemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 群发消息，只允许本地127.0.0.1调用
 * @author LeonSu
 */
@Controller
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private SystemService systemService;

    @PostMapping("/sendMsgToAll")
    @ResponseBody
    public JSONObject sendMessageToAll(HttpServletRequest request, @RequestBody JSONObject data) {
        JSONObject ret = new JSONObject();
        if (!StringUtils.isEmpty(request.getHeader("X-Real-IP")) && !request.getHeader("X-Real-IP").equals("127.0.0.1")) {
            ret.put("code", 1);
            ret.put("errMsg", "非法调用");
            return ret;
        }
        if (!request.getRemoteAddr().equalsIgnoreCase("127.0.0.1")) {
            ret.put("code", 1);
            ret.put("errMsg", "非法调用");
            return ret;
        }
        systemService.sendMessageToAll(data);
        ret.put("code", 0);
        return ret;
    }

    @PostMapping("/sendMsg")
    @ResponseBody
    public JSONObject sendMessage(HttpServletRequest request, @RequestBody JSONObject data) {
        JSONObject ret = new JSONObject();
        if (!StringUtils.isEmpty(request.getHeader("X-Real-IP")) && !request.getHeader("X-Real-IP").equals("127.0.0.1")) {
            ret.put("code", 1);
            ret.put("errMsg", "非法调用");
            return ret;
        }
        if (!request.getRemoteAddr().equalsIgnoreCase("127.0.0.1")) {
            ret.put("code", 1);
            ret.put("errMsg", "非法调用");
            return ret;
        }
        systemService.sendMessage(data.getString("userToken"), data.getJSONObject("data"));
        ret.put("code", 0);
        return ret;
    }
}
